package com.leetcode;

import java.util.HashMap;
import java.util.Map;

/**
 * 677. 键值映射
 * 前缀哈希映射
 * 双map记录所有前缀的值
 *
 * @author fy
 * @date 2022/4/19 18:36
 */
public class Solution677_4 {

    class MapSum {
        private Map<String, Integer> map;
        private Map<String, Integer> prefixMap;

        public MapSum() {
            map = new HashMap<>();
            prefixMap = new HashMap<>();
        }

        public void insert(String key, int val) {
            int delta = val - map.getOrDefault(key, 0);
            map.put(key, val);
            for (int i = 1; i <= key.length(); ++i) {
                String currPrefix = key.substring(0, i);
                prefixMap.put(currPrefix, prefixMap.getOrDefault(currPrefix, 0) + delta);
            }
        }

        public int sum(String prefix) {
            return prefixMap.getOrDefault(prefix, 0);
        }
    }

}
